<script type="text/javascript">
    /**
     * Created by JetBrains RubyMine.
     * User: liupengtao.pt
     * Date: 11-7-17
     * Time: 下午6:38
     * To change this template use File | Settings | File Templates.
     */
    Ext.onReady(function() {

        //准备执行操作时，选择要执行命令的机器，发送到后台的appId与cmdSetDefId参数
        var chooseMachineToExecuteAppId = 1;
        var chooseMachineToExecuteOperationTemplateId = 1;
        //机器名
        var machineName;
        //Application Panel array
        var appPanels = [];
        var csrf_token = $('meta[name="csrf-token"]').attr('content');
        //Current User Application TabPanel
        var appTabPanel = Ext.create('Ext.tab.Panel', {
            region: 'center',
            frame:true,
            split:true
        });

        //应用的中心命令执行状态面板
        //操作模型的定义
        createModel('Command', ['id','name','state','response',{name:'created_at',type: 'date'},{name:'updated_at',type: 'date'}]);

        var actionItemGen = function(preurl, urlAction, msg){
            return {
                icon   : "<%= root_path %>" + 'stylesheets/images/continue.png',
                tooltip: msg,
                handler: function(view, rowIndex, colIndex) {
                            var item = view.getStore().getAt(rowIndex);
                            if(item.isLeaf && !item.isLeaf()){
                                return false;
                            }else{
                                var subId;
                                if(item.isLeaf){
                                    var recordId = item.get("id");
                                    var ids = recordId.split("|");
                                    subId = ids[ids.length - 1];
                                }else{
                                    subId = item.get("id");
                                }
                                Ext.Ajax.request({
                                    url:preurl+"/"+subId+urlAction,
                                    method: 'PUT',
                                    params: {
                                        authenticity_token:csrf_token
                                    },
                                    callback:function(options, success, response) {
                                        var result = Ext.decode(response.responseText);
                                        if (result && result.errors && result.errors.expression) {
                                            Ext.Msg.alert('提示', result.errors.expression[0]);
                                            return;
                                        }
                                        Ext.Msg.alert('提示',msg+"已完成");
                                    }
                                });
                            }
                }
            }
        };

        //一台机器上的所有的命令的执行状态的模型
        //机器列表Model
        createModel('AppMachine', ['id','name','host','chooseToExecute']);
        //Add Current User's Application to the appPanels array.
        function addAppTabPanel(name, id) {
            //请求加载机器上的操作执行状态的队列
            var requestMachineDirectiveStateQueue = [];
            var requestMachineDirectiveInProcess = false;
            //当前应用的机器列表Store
            var machineStore = Ext.create('Ext.data.Store', {
                pageSize: 200,
                model:'AppMachine',
                buffered:true,
                proxy:{
                    type:'ajax',
                    url:"<%= apps_path %>/" + id + '/machines',
                    reader:{
                        type:'json',
                        totalProperty:'totalCount',
                        root:'machines'
                    }
                }
            });
            //操作模板执行前要选择执行操作模板的机器Store
            var chooseMachineToExecuteStore = Ext.create('Ext.data.Store', {
                pageSize: 200,
                model:'AppMachine',
                buffered:true,
                proxy:{
                    type:'ajax',
                    url:"<%= apps_path %>/" + id + '/machines',
                    reader:{
                        type:'json',
                        totalProperty:'totalCount',
                        root:'machines'
                    }
                }
            });
            //应用的左侧面板
            var appLeftPanel = {
                layout:'vbox',
                autoScroll:true,
                collapsible:true,
                split:true,
                region:'west',
                items:[
                    {
                        title:'机器列表',
                        width:450,
                        flex:1,
                        frame:true,
                        layout:'border',
                        items:[
                            {
                                xtype:'gridpanel',
                                id:'machines' + id,
                                split:true,
                                columnLines:true,
                                verticalScrollerType: 'paginggridscroller',
                                invalidateScrollerOnRefresh: false,
                                region:'center',
                                viewConfig: {
                                    stripeRows: true
                                },
                                selModel:Ext.create('Ext.selection.CheckboxModel', {
                                    mode:'MULTI'
                                }),
                                store:machineStore,
                                columns:[
                                    {
                                        header:'主机',
                                        dataIndex:'host',
                                        flex:1
                                    },
                                    {
                                        flex:1,
                                        xtype: 'actioncolumn',
                                        renderer:function() {
                                            return '查看状态';
                                        },
                                        items: [
                                            {
                                                icon   : "<%= root_path %>" + 'stylesheets/images/view.png',
                                                handler: function(view, rowIndex, colIndex) {
                                                    if (Ext.getCmp('centerCardPanel' + id).layout.getActiveItem() != appMachineCommandStateTreePanel) {
                                                        Ext.getCmp('centerCardPanel' + id).layout.setActiveItem(2);
                                                    }
                                                    var machine = view.getStore().getAt(rowIndex);
                                                    if (machine) {
                                                        requestMachineDirectiveStateQueue.push(machine);
                                                        if (!requestMachineDirectiveInProcess) {
                                                            requestMachineDirectiveInProcess = true;
                                                            appMachineCommandStateTreePanel.setTitle("当前应用的" + machine.get('name') + "机器上的命令执行状态");
                                                            machineCommandStore.proxy.url = "<%= apps_path %>/" + id + '/machines/' + machine.get('id') + '/command_state'
                                                            machineCommandStore.load();
                                                        }
                                                    }
                                                }
                                            }
                                        ]
                                    },
                                    {
                                        flex:1,
                                        xtype: 'actioncolumn',
                                        renderer:function() {
                                            return '继续执行';
                                        },
                                        items: [
                                            actionItemGen(
                                                "<%= apps_path %>/" + id + '/machines',
                                                "/reset",
                                                "下发reset指令"
                                            )
                                        ]
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        title:'操作模板',
                        flex:1,
                        width:450,
                        id:'commands' + id,
                        layout:'anchor',
                        frame:true,
                        autoScroll:true,
                        dockedItems:{
                            itemId:'operation_template_toolbar' + id,
                            xtype:'toolbar',
                            items:[
                                {
                                    xtype:'button',
                                    text:'刷新',
                                    iconCls:'refresh',
                                    handler:function() {
                                        var cmdSetPanel = Ext.getCmp('commands' + id);
                                        cmdSetPanel.removeAll();
                                        loadOperationForApp(id);
                                    }
                                }
                            ]
                        }
                    }
                ],
                tbar:[
                    {
                        text:'查看<span style="font-weight: bolder;color: blue;">当前应用</span>的命令执行状态',
                        xtype:'button',
                        iconCls:'view',
                        handler:function() {
                            Ext.getCmp('centerCardPanel' + id).layout.setActiveItem(0);
                        }
                    },
                    {
                        text:'编辑软件包',
                        xtype:'button',
                        iconCls:'add',
                        handler:function() {
                            var editSoftwaresWin = Ext.create('Ext.Window', {
                                title:'编辑软件包',
                                width:400,
                                height:400,
                                layout:'border',
                                items:[
                                    {
                                        region:'center',
                                        xtype:'gridpanel',
                                        store:Ext.create('Ext.data.Store', {
                                            storeId:'softwares' + id,
                                            fields:['id','name'],
                                            proxy:{
                                                url:"<%= apps_path %>/" + id + "/softwares",
                                                type:'ajax',
                                                reader:{
                                                    type:'json'
                                                }
                                            },
                                            autoLoad:true
                                        }),
                                        split:true,
                                        columnLines:true,
                                        viewConfig: {
                                            stripeRows: true
                                        },
                                        plugins:[
                                            Ext.create('Ext.grid.plugin.RowEditing', {
                                                clicksToEdit: 1
                                            })
                                        ],
                                        columns:[
                                            {
                                                text:'软件包名',
                                                dataIndex:'name',
                                                flex:1,
                                                editor: {
                                                    xtype: 'textfield',
                                                    allowBlank: false
                                                }
                                            },
                                            {
                                                flex:1,
                                                xtype: 'actioncolumn',
                                                items: [
                                                    {
                                                        icon   : "<%= root_path %>" + 'stylesheets/images/delete.gif',
                                                        tooltip: '删除当前软件包',
                                                        handler: function(grid, rowIndex, colIndex) {
                                                            var store = this.up('gridpanel').getStore();
                                                            var r = store.getAt(rowIndex);
                                                            Ext.Ajax.request({
                                                                url:"<%= apps_path %>/" + id + "/softwares/" + r.get('id'),
                                                                method:'DELETE',
                                                                params:{
                                                                    authenticity_token:$('meta[name="csrf-token"]').attr('content')
                                                                },
                                                                callback:function (options, success, response) {
                                                                    store.remove(r);
                                                                    store.load();
                                                                }
                                                            });
                                                        }
                                                    }
                                                ]
                                            }
                                        ],
                                        tbar: [
                                            {
                                                text: '增加软件包',
                                                iconCls:'add',
                                                handler : function() {
                                                    var addSoftwareWin = Ext.create('Ext.Window', {
                                                        title:'增加软件包',
                                                        layout:'border',
                                                        width:300,
                                                        height:150,
                                                        items:[
                                                            Ext.create('Ext.form.Panel', {
                                                                region:'center',
                                                                frame:'true',
                                                                url:"<%= apps_path %>/" + id + "/softwares",
                                                                defaultType:'textfield',
                                                                defaults: {
                                                                    labelWidth:90,
                                                                    anchor:'95%'
                                                                },
                                                                items:[
                                                                    {
                                                                        xtype:'hidden',
                                                                        name:'authenticity_token',
                                                                        value:$('meta[name="csrf-token"]').attr('content')
                                                                    },
                                                                    {
                                                                        fieldLabel:'软件包名',
                                                                        name:'software[name]',
                                                                        allowBlank:false,
                                                                        blankText:'软件包名不能为空'
                                                                    }
                                                                ],
                                                                buttons:[
                                                                    {
                                                                        text:'保存',
                                                                        handler:function() {
                                                                            var form = this.up('form').getForm();
                                                                            var that = this;
                                                                            if (form.isValid()) {
                                                                                form.submit({
                                                                                    success: function(form, action) {
                                                                                        Ext.data.StoreManager.lookup('softwares' + id).load();
                                                                                        addSoftwareWin.close();
                                                                                    },
                                                                                    failure: function(form, action) {
                                                                                        Ext.data.StoreManager.lookup('softwares' + id).load();
                                                                                        addSoftwareWin.close();
                                                                                    }
                                                                                });
                                                                            }
                                                                        }
                                                                    },
                                                                    {
                                                                        text:'取消',
                                                                        handler:function() {
                                                                            this.up('window').close();
                                                                        }
                                                                    }
                                                                ]
                                                            })
                                                        ]
                                                    });
                                                    addSoftwareWin.show();
                                                }
                                            }
                                        ],
                                        listeners: {
                                            edit:function(editor, e) {
                                                editor.record.commit();
                                                var record = editor.record;
                                                Ext.Ajax.request({
                                                    url:"<%= apps_path %>/" + id + "/softwares/" + record.get('id'),
                                                    method:'PUT',
                                                    params:{
                                                        authenticity_token:$('meta[name="csrf-token"]').attr('content'),
                                                        'software[name]':record.get('name')
                                                    },
                                                    callback:function(options, success, response) {
                                                    }
                                                });
                                            }
                                        }
                                    }
                                ]
                            });
                            editSoftwaresWin.show();
                        }
                    }
                ]
            };
            machineStore.guaranteeRange(0, 199);
            chooseMachineToExecuteStore.guaranteeRange(0, 199);

            //操作数据store的获取
            var commandStore = Ext.create('Ext.data.TreeStore', {
                model:Command,
                storeId:'commandStore' + id,
                proxy:{
                    type:'ajax',
                    url:"<%= apps_path %>/" + id + '/operations',
                    reader:{
                        type:'json'
                    }
                },
                nodeParam:'key',
                autoLoad:true,
                root:{
                    text:'命令',
                    id:'root',
                    expanded:true
                },
                listeners:{
                    load:function(store) {
                        store.getRootNode().expand(true);
                    }
                }
            });

            var machineCommandProxy = Ext.create('Ext.data.proxy.Ajax', {
                url:'',
                reader:{
                    type:'json'
                }
            });
            machineCommandProxy.afterRequest = function() {
                requestMachineDirectiveStateQueue.shift();
                if (requestMachineDirectiveStateQueue.length > 0) {
                    var machine = requestMachineDirectiveStateQueue.shift();
                    appMachineCommandStateTreePanel.setTitle("当前应用的" + machine.get('name') + "机器上的命令执行状态");
                    machineCommandStore.proxy.url = "<%= apps_path %>/" + id + '/machines/' + machine.get('id') + '/command_state'
                    machineCommandStore.load();
                } else {
                    requestMachineDirectiveInProcess = false;
                }
            };

            //机器的命令执行状态Tree的Store
            var machineCommandStore = Ext.create('Ext.data.TreeStore', {
                //model:MachineCommand,
                model:Command,
                storeId:'machineCommandStore' + id,
                proxy:machineCommandProxy,
                nodeParam:'key',
                root:{
                    text:'命令',
                    id:'root',
                    expanded:true
                }
            });

            //应用的命令执行状态树结构
            var appCenterPanel = Ext.create('Ext.tree.Panel', {
                store:commandStore,
                frame:true,
                title:'当前应用的命令执行状态',
                rootVisible:false,
                autoScroll:true,
                loadMask:true,
                columns: [
                    {
                        xtype:'treecolumn',
                        header:'命令名',
                        dataIndex:'name',
                        flex:1
                    },
                    {
                        header:'命令执行状态',
                        dataIndex:'state',
                        flex:1
                    },
                    {
                        header:'创建时间',
                        dataIndex:'created_at',
                        renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
                        flex:1
                    },
                    {
                        header:'最近更新时间',
                        dataIndex:'updated_at',
                        renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
                        flex:1
                    },
                    {
                        header:'错误清理',
                        xtype: 'actioncolumn',
                        flex:1,
                        renderer: function(value,metaData,record){
                            return record.isLeaf() ? null : "&nbsp;";
                        },
                        items: [
                            actionItemGen(
                                    "<%= apps_path %>/" + id + '/directives',
                                    '/ack',
                                    "错误清理"
                            )
                        ]
                    },
                    {
                        header:'显示结果',
                        xtype: 'actioncolumn',
                        flex:1,
                        renderer: function(value,metaData,record){
                            return record.isLeaf() ? null : "&nbsp;";
                        },
                        items: [
                            {
                                icon   : "<%= root_path %>" + 'stylesheets/images/continue.png',
                                tooltip: '显示执行结果',
                                handler: function(view, rowIndex, colIndex) {
                                    var record = view.getStore().getAt(rowIndex);
                                    if(record.isLeaf()){

                                        var responseWin = Ext.create('Ext.Window', {
                                            title:'指令执行结果',
                                            width:400,
                                            height:100,
                                            layout:'border',
                                            items:[
                                                {
                                                    region:'center',
                                                    xtype     : 'label',
                                                    text:record.get('response')
                                                }
                                            ]
                                        });
                                        responseWin.show();
                                    }
                                }
                            }
                        ]
                    }
                ],
                dockedItems: [
                    {
                        xtype: 'toolbar',
                        dock: 'top',
                        items: [
                            {
                                xtype: 'button',
                                text: '停止实时查看',
                                iconCls:'arrow_refresh',
                                enableToggle:true,
                                listeners:{
                                    toggle:function(button) {
                                        if (button.text === '停止实时查看') {
                                            button.setText('启动实时查看');
                                            Ext.getCmp('refreshDirective').setDisabled(false);
                                            stopPoller();
                                        } else {
                                            button.setText('停止实时查看');
                                            Ext.getCmp('refreshDirective').setDisabled(true);
                                            startPoller();
                                        }
                                    }
                                }
                            },
                            {
                                xtype: 'button',
                                text:'刷新',
                                iconCls:'refresh',
                                id:'refreshDirective',
                                disabled:true,
                                handler:function() {
                                    var commandStore = Ext.data.StoreManager.lookup('commandStore' + id);
                                    commandStore.load();
                                }
                            }
                        ]
                    }
                ]
            });

            var checkDirectiveStatus;

            function startPoller() {
                checkDirectiveStatus = setInterval(function() {
                    var commandStore = Ext.data.StoreManager.lookup('commandStore' + id);
                    commandStore.load();
                }, 5000);
            }

            function stopPoller() {
                clearInterval(checkDirectiveStatus);
            }

            startPoller();

            //当前应用的单台机器上的命令执行状态树结构
            var appMachineCommandStateTreePanel = Ext.create('Ext.tree.Panel', {
                store:machineCommandStore,
                frame:true,
                title:'',
                rootVisible:false,
                autoScroll:true,
                loadMask:true,
                columns: [
                    {
                        xtype:'treecolumn',
                        header:'命令名',
                        dataIndex:'name',
                        flex:1
                    },
                    {
                        header:'命令执行状态',
                        dataIndex:'state',
                        flex:1
                    },
                    {
                        header:'创建时间',
                        dataIndex:'created_at',
                        renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
                        flex:1
                    },
                    {
                        header:'最近更新时间',
                        dataIndex:'updated_at',
                        renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
                        flex:1
                    }
                ],
                dockedItems: [
                    {
                        xtype: 'toolbar',
                        dock: 'top',
                        items: [
                            {
                                xtype: 'button',
                                text: '<span style="font-size: 14px;">刷新</span>',
                                iconCls:'refresh',
                                handler:function() {
                                    Ext.data.StoreManager.lookup('machineCommandStore' + id).load();
                                }
                            }
                        ]
                    }
                ]
            });

            //执行操作模板前选择将要执行该操作模板的机器Panel
            var chooseMachinesToExecutePanel = Ext.create('Ext.grid.Panel', {
                title:'选择执行操作模板的机器',
                split:true,
                columnLines:true,
                disableSelection: true,
                verticalScrollerType: 'paginggridscroller',
                invalidateScrollerOnRefresh: false,
                region:'center',
                viewConfig: {
                    stripeRows: true
                },
                store:chooseMachineToExecuteStore,
                columns:[
                    {
                        xtype: 'rownumberer',
                        width: 50,
                        sortable: false
                    },
                    {
                        header:'机器名',
                        dataIndex:'name',
                        flex:1
                    },
                    {
                        header:'主机',
                        dataIndex:'host',
                        flex:1
                    },
                    {
                        xtype: 'checkcolumn',
                        text: '在当前机器执行',
                        dataIndex: 'chooseToExecute',
                        flex:1
                    }
                ],
                tbar:[
                    {
                        xtype:'button',
                        iconCls:'execute',
                        text:'执行',
                        handler:function() {
                            var choosedMachines = [];
                            chooseMachineToExecuteStore.each(function(record) {
                                if (record.get('chooseToExecute') == true) {
                                    choosedMachines.push(record.get('id'));
                                }
                            });
                            if (choosedMachines.length == 0) {
                                Ext.Msg.alert('提示', '请选择要执行指令的机器！');
                                return;
                            }
                            Ext.Ajax.request({
                                url:"<%= apps_path %>/" + id + '/operations',
                                method:'POST',
                                params:{
                                    authenticity_token:csrf_token,
                                    operation_template_id:chooseMachineToExecuteOperationTemplateId,
                                    choosedMachines:choosedMachines.join(',')
                                },
                                callback:function(options, success, response) {
                                    Ext.Msg.alert('消息', response.responseText);
                                    Ext.getCmp('centerCardPanel' + id).layout.setActiveItem(0);
                                }
                            });
                        }
                    },
                    {
                        xtype:'button',
                        iconCls:'clear',
                        text:'清空所选择的机器',
                        handler:function() {
                            chooseMachineToExecuteStore.each(function(record) {
                                record.set('chooseToExecute', false);
                            });
                        }
                    }
                ]
            });
            //用户界面的中心card面板
            var centerCardPanel = Ext.create('Ext.panel.Panel', {
                layout:'card',
                region:'center',
                border:false,
                id:'centerCardPanel' + id,
                activeItem:0,
                items:[
                    appCenterPanel,
                    chooseMachinesToExecutePanel,
                    appMachineCommandStateTreePanel
                ]
            });
            //一个应用的总面板
            var appPanel = {
                title:name,
                xtype:'panel',
                layout:'border',
                split:true,
                collapsible:true,
                items:[
                    appLeftPanel,
                    centerCardPanel
                ]
            };
            appPanels[appPanels.length] = appPanel;
        }

        //为应用加载操作模板
        function loadOperationForApp(appId) {
            Ext.Ajax.request({
                url:"<%= apps_path %>/" + appId + '/operation_templates',
                callback:function(options, success, response) {
                    var cmdSetStr = response.responseText;
                    var cmdSet = Ext.decode(cmdSetStr);
                    var cmdSetPanel = [];
                    for (var j = 0,len = cmdSet.length; j < len; j++) {
                        var actions = cmdSet[j].actions;
                        if (!actions) {
                            continue;
                        }
                        var columnCount = cmdSet[j].actions.length + 1;
                        var cmdSetPanelCmps = [];
                        cmdSetPanelCmps[cmdSetPanelCmps.length] = {
                            xtype:'label',
                            flex:cmdSet[j].flex,
                            html:cmdSet[j].name
                        };
                        for (var k = 1; k < columnCount; k++) {
                            cmdSetPanelCmps[cmdSetPanelCmps.length] = {
                                flex:cmdSet[j].actions[k - 1].flex,
                                xtype:'button',
                                text:cmdSet[j].actions[k - 1].name,
                                handler:
                                        (function(url, method, type, operationTemplateId) {
                                            return function() {
                                                var breakdown = false;
                                                if (type.toLowerCase() == 'simple') {
                                                    var selectedMachines = Ext.getCmp('machines' + appId).getSelectionModel().getSelection();
                                                    var choosedMachines = [];
                                                    for (var i = 0; i < selectedMachines.length; i++) {
                                                        choosedMachines.push(selectedMachines[i].get('id'));
                                                    }
                                                    if (choosedMachines.length == 0) {
                                                        Ext.Msg.alert('提示', '请选择要执行指令的机器！');
                                                        return;
                                                    }
                                                    Ext.Ajax.request({
                                                        url:"<%= apps_path %>/" + appId + '/operations',
                                                        method:'POST',
                                                        params:{
                                                            authenticity_token:csrf_token,
                                                            operation_template_id:operationTemplateId,
                                                            choosedMachines:choosedMachines.join(',')
                                                        },
                                                        callback:function(options, success, response) {
                                                            Ext.Msg.alert('消息', response.responseText);
                                                        }
                                                    });
                                                    return;
                                                } else if (type == 'delete') {
                                                    Ext.Msg.show({
                                                        title:'提示',
                                                        msg: '您确定要删除当前操作模板吗？',
                                                        buttons: Ext.Msg.YESNOCANCEL,
                                                        fn: function(btn) {
                                                            if (btn == 'yes') {
                                                                Ext.Ajax.request({
                                                                    url:url,
                                                                    method:method,
                                                                    params:{
                                                                        authenticity_token:csrf_token,
                                                                        operation_template_id:operationTemplateId
                                                                    },
                                                                    callback:(function(type) {
                                                                        return function(options, success, response) {
                                                                            var cmdSetPanel = Ext.getCmp('commands' + appId);
                                                                            cmdSetPanel.removeAll();
                                                                            loadOperationForApp(appId);
                                                                        }
                                                                    })(type)
                                                                })
                                                            }
                                                        },
                                                        icon: Ext.window.MessageBox.QUESTION
                                                    });
                                                } else if (type == 'multi') {
                                                    Ext.Ajax.request({
                                                        url:url,
                                                        method:method,
                                                        params:{
                                                            authenticity_token:csrf_token,
                                                            operation_template_id:operationTemplateId
                                                        },
                                                        callback:(function(type) {
                                                            return function(options, success, response) {
                                                                var respondUrl = Ext.decode(response.responseText).url;
                                                                var multiWin = Ext.create('Ext.Window', {
                                                                    width:720,
                                                                    height:544,
                                                                    title:'修改操作模板',
                                                                    autoScroll:true,
                                                                    items:[
                                                                        {
                                                                            autoScroll:true,
                                                                            html:getIFrameForEditOperation(respondUrl, 700, 500)
                                                                        }
                                                                    ]
                                                                });
                                                                multiWin.show();
                                                            }
                                                        })(type)
                                                    })
                                                } else if (type == 'group') {
//                                                    chooseMachineToExecuteAppId = appId;
//                                                    chooseMachineToExecuteOperationTemplateId = cmdSetDefId;
                                                    var executeCommandWin = Ext.create('Ext.Window', {
                                                        title:'选择执行方式',
                                                        width:300,
                                                        height:200,
                                                        layout:'border',
                                                        items:[
                                                            {
                                                                xtype:'fieldset',
                                                                region:'center',
                                                                frame:true,
                                                                items:[
                                                                    {
                                                                        xtype: 'radiogroup',
                                                                        columns: 2,
                                                                        margin:'10 0 0 0',
                                                                        id:'execute_strategy',
                                                                        items: [
                                                                            {
                                                                                name:'execute_strategy',
                                                                                boxLabel:'全部执行',
                                                                                inputValue:1,
                                                                                checked:true,
                                                                                listeners:{
                                                                                    change:function(field, newValue, oldValue) {
                                                                                        if (newValue == true) {
                                                                                            Ext.getCmp('groupCount').hide();
                                                                                            Ext.getCmp('roomGroup').hide();
                                                                                        }
                                                                                    }
                                                                                }

                                                                            },
                                                                            {
                                                                                name:'execute_strategy',
                                                                                boxLabel:'分组执行',
                                                                                inputValue:2,
                                                                                listeners:{
                                                                                    change:function(field, newValue, oldValue) {
                                                                                        if (newValue == true) {
                                                                                            Ext.getCmp('groupCount').show();
                                                                                            Ext.getCmp('roomGroup').show();
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        ]
                                                                    },
                                                                    {
                                                                        xtype:'combo',
                                                                        id:'roomGroup',
                                                                        fieldLabel:'请选择机房',
                                                                        queryMode: 'remote',
                                                                        displayField: 'name',
                                                                        valueField: 'id',
                                                                        store:Ext.create('Ext.data.Store', {
                                                                            fields:['id','name'],
                                                                            proxy:{
                                                                                url:"<%= apps_path %>/" + appId + "/rooms",
                                                                                type:'ajax',
                                                                                reader: {
                                                                                    type:'json'
                                                                                }
                                                                            }
                                                                        }),
                                                                        editable:false,
                                                                        hidden:true
                                                                    },
                                                                    {
                                                                        xtype:'numberfield',
                                                                        id:'groupCount',
                                                                        fieldLabel:'请输入分组数',
                                                                        hidden:true,
                                                                        minValue:1
                                                                    }
                                                                ]
                                                            }
                                                        ],
                                                        buttons:[
                                                            {
                                                                text:'确定',
                                                                handler:function() {
                                                                    var fieldset = Ext.getCmp('execute_strategy');
                                                                    if (fieldset.getChecked()[0].getGroupValue() == 1) {
                                                                        Ext.Ajax.request({
                                                                            url:"<%= apps_path %>/" + appId + '/operations',
                                                                            method:'POST',
                                                                            params:{
                                                                                authenticity_token:csrf_token,
                                                                                operation_template_id:operationTemplateId
                                                                            },
                                                                            callback:function(options, success, response) {
                                                                                Ext.Msg.alert('消息', response.responseText);
                                                                            }
                                                                        });
                                                                    } else {
                                                                        Ext.Ajax.request({
                                                                            url:"<%= apps_path %>/" + appId + "/operation_templates/" + operationTemplateId + "/group_execute",
                                                                            method:'POST',
                                                                            params:{
                                                                                authenticity_token:csrf_token,
                                                                                room_id:Ext.getCmp('roomGroup').value,
                                                                                group_count:Ext.getCmp('groupCount').value
                                                                            },
                                                                            callback:function(options, success, response) {
                                                                                Ext.Msg.alert('消息', response.responseText);
                                                                            }
                                                                        });
                                                                    }
                                                                    executeCommandWin.close();
                                                                }
                                                            }
                                                        ]
                                                    });
                                                    executeCommandWin.show();
                                                }
                                            }
                                        })(cmdSet[j].actions[k - 1].url, cmdSet[j].actions[k - 1].method, cmdSet[j].actions[k - 1].type, cmdSet[j].id)
                            }
                        }
                        cmdSetPanel[cmdSetPanel.length] = {
                            xtype:'panel',
                            border:false,
                            layout:'hbox',
                            anchor:'100%',
                            frame:true,
                            items: [
                                cmdSetPanelCmps
                            ]
                        }
                    }
                    if (cmdSet.length > 0 && cmdSet[0].add === true) {
                        var toolbar = Ext.getCmp('commands' + appId)
                                .getDockedComponent('operation_template_toolbar' + appId);
                        if (toolbar.items.getCount() == 1) {
                            Ext.getCmp('commands' + appId)
                                    .getDockedComponent('operation_template_toolbar' + appId)
                                    .add(['-',{
                                xtype:'button',
                                text:'增加',
                                iconCls:'add',
                                id:'appAddButton' + appId,
                                handler:function() {
                                    addOperationWindow(this.id.substring(this.id.length - 1));
                                }
                            }]);
                        }
                    }
                    Ext.getCmp('commands' + appId).add(cmdSetPanel);
                }
            });
        }

        //增加操作模板窗口
        function addOperationWindow(appId) {
            //请求获取命令组数据并解析
            var cmdGroupNodes = [];
            Ext.Ajax.request({
                url:"<%= directive_groups_path %>",
                callback:function(options, success, response) {
                    var cmdGroups = Ext.decode(response.responseText);
                    for (var i = 0; i < cmdGroups.length; i++) {
                        var cmdGroupNode = {};
                        var cmdGroup = cmdGroups[i];
                        cmdGroupNode.id = 'directive_group' + cmdGroup.id;
                        cmdGroupNode.text = cmdGroup.name;

                        //为命令组增加命令
                        var cmdDefs = cmdGroup.directive_templates;
                        if (cmdDefs.length == 0) {
                            cmdGroupNode.leaf = true;
                        } else {
                            var children = [];
                            for (var j = 0; j < cmdDefs.length; j++) {
                                var cmdDef = {};
                                cmdDef.id = 'directive_template' + cmdDefs[j].id;
                                cmdDef.text = cmdDefs[j].name;
                                cmdDef.leaf = true;

                                children[children.length] = cmdDef;
                            }
                            cmdGroupNode.children = children;
                        }
                        cmdGroupNodes[cmdGroupNodes.length] = cmdGroupNode;
                    }
                    var cmdGroupStore = Ext.create('Ext.data.TreeStore', {
                        root: {
                            text: '命令组列表',
                            expanded: true,
                            children:cmdGroupNodes
                        },
                        folderSort: true,
                        sorters: [
                            {
                                property: 'id',
                                direction: 'ASC'
                            }
                        ]
                    });

                    //增加操作模板时系统所有的命令组树

                    var cmdGroupTreePanel = Ext.create('Ext.tree.Panel', {
                        title: '当前系统所有命令',
                        region:'west',
                        store:cmdGroupStore,
                        width:200,
                        autoScroll:true,
                        loadMask:true,
                        collapsible:true,
                        viewConfig: {
                            plugins: {
                                ptype: 'treeviewdragdrop',
                                enableDrop:false
                            }
                        },
                        selModel:{
                            mode:'MULTI'
                        },
                        listeners:{
                            itemremove:function(parent, node) {
                                var nextSibling = node.nextSibling;
                                var newNode = node.createNode({
                                    id:node.data.id,
                                    text:node.data.text,
                                    leaf:node.data.leaf
                                });
                                if (!node.isLeaf()) {
                                    var childNodes = node.childNodes;
                                    for (var i = 0,len = childNodes.length; i < len; i++) {
                                        newNode.appendChild({
                                            id:childNodes[i].data.id,
                                            text:childNodes[i].data.text,
                                            leaf:childNodes[i].data.leaf
                                        });
                                    }
                                }
                                if (nextSibling) {
                                    parent.insertBefore(newNode, nextSibling);
                                } else {
                                    parent.appendChild(newNode);
                                }
                                if (node.isExpanded()) {
                                    newNode.expand();
                                }
                                node.remove(true);
                            }
                        }
                    });
                    cmdGroupTreePanel.getSelectionModel().on('select', function(selModel, record) {
                        var nodes = selModel.getSelection();
                        if (record.isLeaf() && nodes.indexOf(record.parentNode) > -1) {
                            selModel.deselect(record);
                        }
                        if (!record.isLeaf() && !record.isRoot()) {
                            record.eachChild(function(child) {
                                selModel.deselect(child);
                            });
                        }
                        if (record.isRoot()) {
                            selModel.deselect(record);
                        }
                    });

                    //增加操作模板时点击增加时，增加命令到操作模板
                    function addOperation() {
                        var expression = '';
                        //获取操作模板表达式
                        cmdSetTreePanel.getRootNode().eachChild(function(child) {
                            var data = child.data;
                            expression += data._id.substring('directive_template'.length) + (data.allowFailure == true ? '|true' : '');
                            if (!child.isLast()) {
                                expression += ',';
                            }
                        });
                        if (!expression || expression.trim().length == 0) {
                            Ext.Msg.alert('提示', '您没有为要创建的操作添加原子指令。');
                            return;
                        }
                        //增加操作模板完成后刷新用户界面中的操作模板信息
                        Ext.Ajax.request({
                            url:"<%= apps_path %>/" + appId + '/operation_templates',
                            method:'POST',
                            params:{
                                authenticity_token:csrf_token,
                                'operation_template[name]':Ext.getCmp('cmdSetName').value,
                                'operation_template[expression]':expression
                            },
                            callback:function(options, success, response) {
                                var result = Ext.decode(response.responseText);
                                if (result.errors.expression) {
                                    Ext.Msg.alert('提示', result.errors.expression);
                                    return;
                                }
                                Ext.getCmp('savedStatus').setText('操作模板增加成功');
                                var cmdSetPanel = Ext.getCmp('commands' + appId);
                                cmdSetPanel.removeAll();
                                loadOperationForApp(appId);
                                addOperationWin.close();
                            }
                        });
                    }

                    var cmdSetTreeStore = Ext.create('Ext.data.TreeStore', {
                        root: {
                            text: '',
                            expanded: true
                        },
                        fields:['_id','text','allowFailure']
                    });

                    //增加操作模板时向操作模板中增加命令组中的命令信息,此方法被多个操作共用
                    function addDirectiveGroupToOperation(parent, node, refNode) {
                        if (!node.isLeaf()) {
                            node.eachChild(function(child) {
                                var newChild = parent.createNode({
                                    _id:child.data.id,
                                    text:child.data.text,
                                    leaf:child.data.leaf,
                                    allowFailure:false
                                });
                                setTimeout(function() {
                                    parent.insertBefore(newChild, refNode);
                                }, 10);
                            });
                            setTimeout(function() {
                                node.removeAll();
                                node.remove();
                            }, 10);
                        } else if (node.data.allowFailure !== true) {
                            if (!node.data._id) {//当增加文件夹中的所有命令时需要注意的地方。
                                node.data._id = node.data.id;
                            }
                            node.data.allowFailure = false;
                        }
                    }

                    //增加操作模板时的操作模板树结构信息
                    var cmdSetTreePanel = Ext.create('Ext.tree.Panel', {
                        title:'操作模板所有命令',
                        collapsible:true,
                        region:'center',
                        viewConfig: {
                            plugins: {
                                ptype: 'treeviewdragdrop'
                            }
                        },
                        autoScroll:true,
                        loadMask:true,
                        listeners:{
                            //向操作模板中增加命令
                            iteminsert:function(parent, node, refNode) {
                                addDirectiveGroupToOperation(parent, node, refNode);
                            },
                            itemappend:function(parent, node, index) {
                                addDirectiveGroupToOperation(parent, node);
                            }
                        },
                        tbar: [
                            {
                                xtype: 'button',
                                iconCls:'add',
                                text: '保存',
                                handler:function() {
                                    var name = Ext.getCmp('cmdSetName').value;
                                    if (!name || name.trim().length == 0) {
                                        Ext.Msg.alert('提醒', '请输入操作模板的名字！');
                                        return;
                                    }
                                    cmdSetTreePanel.getRootNode().commit();
                                    addOperation();
                                }
                            }
                        ],
                        store:cmdSetTreeStore,
                        columns: [
                            {
                                xtype:'treecolumn',
                                text: '命令',
                                width:220,
                                dataIndex: 'text'
                            },
                            {
                                xtype:'treecheckcolumn',
                                text: '允许失败',
                                dataIndex: 'allowFailure'
                            },
                            {
                                xtype: 'actioncolumn',
                                width: 20,
                                items: [
                                    {
                                        icon   :"<%= root_path %>" + 'stylesheets/images/delete.gif',
                                        tooltip: '删除当前命令',
                                        handler: function(tree, rowIndex, colIndex) {
                                            var root = this.up('treepanel').getRootNode();
                                            if (rowIndex == 0) {
                                                root.removeAll();
                                            } else {
                                                var nodeToDeleted = root.getChildAt(rowIndex - 1);
                                                nodeToDeleted.remove();
                                            }
                                        }
                                    }
                                ]
                            }
                        ]
                    });

                    //增加操作模板时显示操作模板的信息面板，包括操作模板名与树状信息
                    var cmdSetPanel = Ext.create('Ext.panel.Panel', {
                        title:'操作模板',
                        region:'center',
                        collapsible:true,
                        layout:'border',
                        items:[
                            {
                                layout:'column',
                                frame:true,
                                region:'north',
                                items:[
                                    {
                                        xtype:'textfield',
                                        fieldLabel:'操作模板名',
                                        id:'cmdSetName',
                                        columnWidth:0.5,
                                        enableKeyEvents:true,
                                        listeners:{
                                            keyup:function(field) {
                                                cmdSetTreePanel.getRootNode().set('text', field.getValue());
                                            }
                                        }
                                    },
                                    {
                                        xtype:'label',
                                        columnWidth:0.5,
                                        id:'savedStatus'
                                    }
                                ]
                            },
                            cmdSetTreePanel
                        ]
                    });
                    //增加操作模板的窗口
                    var addOperationWin = Ext.create('Ext.Window', {
                        title:'增加操作模板',
                        layout: {
                            type: 'border',
                            padding: 5
                        },
                        defaults: {
                            split: true
                        },
                        items: [
                            cmdGroupTreePanel,
                            cmdSetPanel
                        ],
                        width:700,
                        height:500
                    });
                    addOperationWin.show();
                }
            });
        }

        //编辑操作模板时的iframe标签
        function getIFrameForEditOperation(url, width, height) {
            return '<iframe src="' + url + ' " width="' + width + '" height="' + height + '"' +
                    '></iframe>'
        }

        //Request Current User's Applications
        Ext.Ajax.request({
            url:"<%= apps_path %>",
            callback:function(options, success, response) {
                var result = response.responseText;
                var obj = Ext.decode(result);
                if (obj.length == 0) {
                    var title = '<span style=\"display:block;font-size:15px;font-weight:bolder;width:' + 6 + 'px;margin: 0 auto;\">您没有要管理的应用</span>';
                    appTabPanel.setTitle(title);
                }
                for (var i = 0; i < obj.length; i++) {
                    addAppTabPanel(obj[i].name, obj[i].id);
                }
                appTabPanel.add(appPanels);//Add to addTabPanel

                for (var i = 0; i < obj.length; i++) {
                    //此处获取App的操作模板列表，url为apps/:id/operation_templates
                    loadOperationForApp(obj[i].id);
                }
            }
        });

        //The Welcome bar in the top
        var welcomePanel = {
            region:'north',
            contentEl:'north',
            frame:true
        };

        //The main panel
        var userMainPanel = Ext.create('Ext.Viewport', {
            renderTo:'main',
            layout: {
                type: 'border',
                padding: 5
            },
            defaults: {
                split:true
            },
            items: [
                welcomePanel,
                appTabPanel
            ]
        });
    });
</script>
